from datetime import datetime
from django.conf import settings
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from bigevents_admin.authenticate import JWTAuth
from bigevents_admin.serializers.articles import ArticleSerializer, ArticleListSerializer, OneArticleSerializer, \
    EditArticleSerializer
from article.models import Article
from bigevents_admin.utils import PageNum, upload_img


class AddArticleView(APIView):
    """发布新文章"""
    authentication_classes = (JWTAuth,)

    def post(self, request):
        if request.user is None:
            return Response({'status': 1, 'message': '发布文章失败！'})
        data = request.data
        img = data.get('cover_img')
        data = data.dict()
        author_id = int(request.user.id)
        data['author_id'] = author_id
        data['cate_id'] = int(data['cate_id'])
        data['pub_date'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        serializer = ArticleSerializer(data=data)

        if not serializer.is_valid():
            return Response({'status': 1, 'message': '发布文章失败！'})

        article = serializer.save()
        # 上传图片至fdfs，并将返回的文件索引存储在数据库
        article.cover_img = upload_img(img)
        article.save()
        return Response({'status': 0, 'message': '发布文章成功！'})


class ArticleListView(ListAPIView):
    """获取文章的列表数据"""
    authentication_classes = (JWTAuth,)
    pagination_class = PageNum
    queryset = Article.objects.filter(is_delete=False)
    serializer_class = ArticleListSerializer

    def get_queryset(self):
        # 获取用户id
        author_id = self.request.user.id
        cate_id = self.request.query_params.get('cate_id')
        # 前端传来的state参数是'已发布'，'草稿'
        state = self.request.query_params.get('state')
        if state == '已发布':
            state = 1
        elif state == '草稿':
            state = 2
        # 根据cate_id和state的值，指定对应的查询集
        if state == '' and cate_id == '':
            queryset = self.queryset.filter(author_id=author_id)
        if cate_id and state:
            queryset = self.queryset.filter(cate_id=int(cate_id), state=state, author_id=author_id)
        if cate_id or state:
            if not cate_id:
                queryset = self.queryset.filter(state=state, author_id=author_id)
            if not state:
                queryset = self.queryset.filter(cate_id=int(cate_id), author_id=author_id)

        return queryset


class DeleteArticleView(APIView):
    """根据 Id 删除文章数据"""
    authentication_classes = (JWTAuth,)

    def get(self, request, id):
        try:
            article = Article.objects.get(id=id)
        except Exception as e:
            return Response({'status': 1, 'message': '删除失败!'})
        article.is_delete = True
        article.save()
        return Response({'status': 0, 'message': '删除成功!'})


class ArticleView(APIView):
    """根据 Id 获取文章详情"""
    authentication_classes = (JWTAuth,)

    def get(self, request, id):
        try:
            article = Article.objects.get(id=id)
        except Exception as e:
            return Response({'status': 1, 'message': '获取文章失败!'})

        serializer = OneArticleSerializer(article)
        data = serializer.data
        if data['cover_img'] is not None:
            # 拼接图片地址:ip+file_id
            cover_img = settings.FDFS_BASE_URL + article.cover_img.url
            data['cover_img'] = cover_img
        return Response({'status': 0, 'message': '获取文章成功!', 'data': data})


class EditArticleView(APIView):
    authentication_classes = (JWTAuth,)

    def post(self, request):

        serializer = EditArticleSerializer(data=request.data)
        try:
            serializer.is_valid()
        except Exception as e:
            return Response({'status': 1, 'message': '修改文章失败!'})

        data = serializer.validated_data
        # 获取文章id
        id = request.data.get('id')
        # 更新文章的内容
        Article.objects.filter(id=id).update(**data)
        article = Article.objects.get(id=id)
        img = request.data.get('cover_img')
        # 将图片上传至fdfs，并返回文件索引
        article.cover_img = upload_img(img)
        # 将文章的cover_img字段更新为fdfs的文件索引
        article.save()
        return Response({'status': 0, 'message': '修改文章成功!'})
